import {
	baseUrl
} from "./variables.js"
import {
	STATUS_CODE
} from "./variables.js"
import {
	removeItem,
	getItem
} from "@/utils/selfLocalStorage.js"

/**
 *  promise 形式  showToast
 * @param {object} param0 参数
 */

let ajaxTime = 0

export default {
	/**
	 * @param paset 上传配置
	 * @return  Promise
	 */
	request: (paset) => {
		ajaxTime++
		uni.showLoading({
			title: '加载中',
			mask: true
		})


		const header = {
			...paset.header,
			'Authorization': getItem('token') || "",
			'content-type': 'application/json',
			'Access-Control-Allow-Origin': ''
		}
		return new Promise((resolve, reject) => {
			uni.request({
				...paset,
				header,
				url: baseUrl + paset.url,
				success: (res) => {
					const result = res.data
					if (result.code === STATUS_CODE.NOLOGIN) {
						uni.showToast({
							title: '登录过期',
							icon: 'error',
							duration: 2000
						})
						// 删除本地数据
						removeItem("uid");
						removeItem("token");
						// 未登录
						uni.navigateTo({
							url: "/pages/login/login"
						})
					}
					resolve(result)
				},
				fail: (err) => {
					uni.showToast({
						title: '网络错误',
						icon: 'error',
						duration: 2000
					})
				},
				complete: () => {
					ajaxTime--
					if (ajaxTime === 0) {
						uni.hideLoading()
					}
				}
			})
		})
	},

	/**
	 * @param url 上传位置
	 * @param file 文件对象 图片
	 * @param types 文件类型  默认图片
	 * @return  Promise
	 */
	pushFile(url, filem, types = 'image') {

		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: `${baseUrl}${url}`,
				filePath: filem,
				name: "file",
				fileType: types,
				header: {
					'Authorization': getItem('token') || ""
				},
				success: (uploadFileRes) => {
					resolve(JSON.parse(uploadFileRes.data))
				},
				fail(e) {
					console.log("this is errormes " + e.message);
				},
			});
		})
	}
}


export function checkLogin() {
	// 构建请求参数
	const paset = {
		url: "/user/check",
		method: "GET"
	}

	const header = {
		...paset.header,
		'Authorization': getItem('token') || "",
		'content-type': 'application/json',
		'Access-Control-Allow-Origin': ''
	}
	return new Promise((resolve, reject) => {
		uni.request({
			...paset,
			header,
			url: baseUrl + paset.url,
			success: (res) => {
				const result = res.data
				if (result.code === STATUS_CODE.NOLOGIN) {
					// token过期 删除
					removeItem("uid")
					removeItem("token");
				}
				resolve(result)
			},
			fail: (err) => {
				uni.showToast({
					title: '网络错误',
					icon: 'error',
					duration: 2000
				})
			}
		})
	})
}


